<template>
  <div>
    <van-nav-bar title="区域申请" fixed left-arrow @click-left="$utils.back($route.path)" />
    <div class="has-top">
      <van-form ref="subForm" class="mg-25 mt-20">
        <div class="bg-primary br-12 pd-25">
          <p class="color-white fs-28">请选择您要申请的区域，并填写相关资料！</p>
          <div class="mt-20 br-12 bg-white">
            <div class="flex-s-c ptb-36 plr-30 br-12 shadow-box" @click="showAreaLevel = !showAreaLevel">
              <p>
                <svg-icon icon-class="areaApply" class="fs-36 mr-10" />
                <span class="fs-28">申请区域等级</span>
              </p>
              <p>
                <span class="color-primary fs-36 right-triangle">{{ levelName }}</span>
              </p>
            </div>
            <van-popup v-model="showAreaLevel" position="bottom">
              <van-picker
                v-model="levelName"
                item-height="45"
                visible-item-count="4"
                show-toolbar
                title="申请区域等级"
                :columns="levelList"
                @confirm="areaLevelOnConfirm"
                @cancel="showAreaLevel = false"
              />
            </van-popup>
            <p class="color-warning plr-30 ptb-15 fs-30" v-if="regionName !== ''">申请此等级的区域所需金额¥{{ levelMoney }}元</p>
          </div>
        </div>

        <div class="mt-20 br-12 ofh">
          <van-field
            v-model="applyInfo.userName"
            name="姓名"
            label="姓名"
            placeholder="请输入姓名"
            :rules="[{ required: true, message: ' ' }]"
          />
          <van-field
            v-model="applyInfo.userTel"
            name="电话"
            label="电话"
            placeholder="请输入电话号码"
            :rules="[{ required: true, message: ' ' }]"
          />
          <van-field
            v-model="applyInfo.userAddress"
            name="联系地址"
            label="联系地址"
            placeholder="请输入联系地址"
          />
          <van-field
            readonly
            right-icon="arrow"
            clickable
            name="picker"
            :value="regionName"
            label="申请区域"
            placeholder="请选择"
            :rules="[{ required: true, message: ' ' }]"
            @click="openAddressPicker"
          />
          <van-popup v-model="addressPicker" position="bottom">
            <applyAreaSelect :max-level="maxLevel" :address-data="addressData" @pickArea="pickArea" />
          </van-popup>
        </div>
				<div class="bg-white pd-24 mt-30 br-12 fs-28">
					<van-radio-group v-model="applyInfo.payType" v-for="(item,index) in payWayList" :key="index" class="mb-30">
						
						<van-radio :name="item.PayType" checked-color="#2cd334" class="choose" label-position="left" @click="changeRadio(index,item)">
							<img v-if="item.PayTypeName === '余额支付'" src="../../assets/images/balancePay.png"/>
							<img v-if="item.PayTypeName === '微信支付'" src="../../assets/images/wechatPay.png"/>
							<img v-if="item.PayTypeName === '线下支付'" src="../../assets/images/offlinePay.png" />
							<img v-if="item.PayTypeName === '富友支付'" src="../../assets/images/fuyouPay.png" />
							{{ item.PayTypeName }}{{ item.PayTypeName === '余额支付'? '(' + item.Balance + ')': ''  }}
						</van-radio>
					</van-radio-group>
				</div>
				
        <div class="mt-20 br-12 ofh bg-white pt-32 " style="padding-left:0.426666rem;padding-right:0.426666rem;" v-if="applyInfo.payType === 1">
          <p class="mb-28 fs-26">请选择付款方式</p>
          <div class="bank-box mb-24">
            <div class="bank-list hb arrow flex-v-c" @click="showBankList = !showBankList">
              <svg-icon v-if="bankInfo.AccountType===0" icon-class="bank" class="fs-64 mr-10" />
              <svg-icon v-if="bankInfo.AccountType===2" icon-class="alipay" class="fs-64 mr-10" />
              <svg-icon v-if="bankInfo.AccountType===1" icon-class="wechatpay" class="fs-64 mr-10" />
              <span class="fs-28">{{ bankInfo.AccountTypeName }}</span>
            </div>
            <div v-show="bankInfo.AccountType===0" class="bank-info">
              <p class="bank-info-p">
                <span class="bank-info-title">开户行：</span>
                <span>{{ bankInfo.BankTypeName+bankInfo.Branch }}</span>
              </p>
              <p class="bank-info-p">
                <span class="bank-info-title">收款账户：</span>
                <span>{{ bankInfo.Number }}</span>
              </p>
              <p class="bank-info-p">
                <span class="bank-info-title">收款人：</span>
                <span>{{ bankInfo.AccountName }}</span>
              </p>
            </div>
            <div v-show="bankInfo.AccountType===1||bankInfo.AccountType===2" class="bank-img">
              <img-box class="is-200 tac img" :img-url="bankInfo.PayQrUrl" />
              <p class="mt-20 fs-20">请使用{{ bankInfo.AccountTypeName }}识别二维码完成支付</p>
            </div>
          </div>
          <van-popup v-model="showBankList" position="bottom">
            <van-picker
              v-model="bankInfo.AccountTypeName"
              item-height="45"
              visible-item-count="4"
              show-toolbar
              title="付款方式"
              :columns="bankList"
              @confirm="bankTypeOnConfirm"
              @cancel="showBankList = false"
            />
          </van-popup>
          <p class="mb-28 fs-26">上传付款凭证</p>
          <van-uploader
            v-model="imagesArr"
            max-count="3"
            :after-read="imageAfterRead"
            @delete="deleteImage"
          />
          <p class="fs-22 flex-s-fs">
            <span class="flex-s-0 lh-lg" style="padding-top:0.266666rem">备注:</span>
            <van-field v-model="applyInfo.remark" type="textarea" class="fs-22" placeholder="请在此处填写留言~" />
          </p>
        </div>
        <div class="btn-box pt-40 pb-60 flex-center">
          <van-button class="br-44 solid-btn" type="info" @click="handleSubmit(1)">提交申请</van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script>
import imgBox from 'components/imgBox'
import applyAreaSelect from 'components/address/applyAreaSelect'
import { AreaApplyInitData, SubmitAreaApply, GetAreaApplyMoneyByUser } from 'api/areaApply'
import { GetList } from 'api/order'
import { upLoad } from 'api/upload'
import { GetBusinessFunction } from 'api/businessSetting'
export default {
  components: {
    imgBox,
    applyAreaSelect
  },
  data() {
    return {
      addressPicker: false,
      addressData: {},
      maxLevel: 0,
      levelName: '',
      levelMoney: 0,
      showAreaLevel: false,
      levelList: [],
      applyInfo: {
        userName: '',
        userTel: '',
        applyImages: '',
        remark: '',
        userAddress: '',
				payType: 0,
      },
      bankList: [],
      showBankList: false,
      imagesArr: [],
      tempImageArr: [],
      bankInfo: {},
      regionName: '',
			switch275: 0,
			payWayList: [
				{
					PayTypeName: '线下支付',
					PayType: 1
				}
			], //支付方式列表
    }
  },
  watch: {
    maxLevel(newVal, oldVal) {
      this.addressData = {}
      this.regionName = ''
    }
  },
  created() {
    this.AreaApplyInitData()
		this.GetBusinessFunction()
		this.GetList()
  },
  methods: {
		//获取可选支付方式
		GetList(){
			const obj = {}
			obj.usageScenario = 6
			GetList(obj).then(res => {
				if(res.Data && res.Data.length > 0){
					this.applyInfo.payType = res.Data[0].PayType
					this.payWayList = res.Data
				}else{
					this.applyInfo.payType = 1
				}
			})
		},
		changeRadio(index,item) {
      this.applyInfo.payType = item.PayType
    },
		//获取开关权限
		GetBusinessFunction(){
      GetBusinessFunction(275).then(res => {
        if (res) {
          this.switch275 = res.Data[0].Value;	
        }
      })
    },
    pickArea(areaObj) {
      console.log(areaObj)
      this.regionName = (areaObj.ProvinceName || '') + (areaObj.CityName || '') + (areaObj.AreaName || '') + (areaObj.StreetName || '')
      switch (this.maxLevel) {
        case 3:
          this.applyInfo.areaId = areaObj.ProvinceId
          break
        case 4:
          this.applyInfo.areaId = areaObj.CityId
          break
        case 5:
          this.applyInfo.areaId = areaObj.AreaId
          break
        case 6:
          this.applyInfo.areaId = areaObj.StreetId
          break
      }
      this.addressPicker = false
			if(this.switch275 === 1){
				this.GetAreaApplyMoneyByUser()
			}
    },
		GetAreaApplyMoneyByUser(){
			const obj = {}
			obj.level = this.maxLevel
			obj.areaId = this.applyInfo.areaId
			GetAreaApplyMoneyByUser(obj).then(res => {
				if(res.State === 1){
					this.levelMoney = res.Data.Money
					this.applyInfo.BaseMoney = res.Data.BaseMoney
					this.applyInfo.Money = res.Data.Money
				}
			})
		},
    areaLevelOnConfirm(value) {
      console.log(value)
      this.maxLevel = value.Level
      this.levelName = value.text
      this.showAreaLevel = false
    },
    bankTypeOnConfirm(value) {
      console.log(value)
      this.bankInfo = value
      this.showBankList = false
    },
    openAddressPicker() {
      if (this.maxLevel === 0) {
        this.$toast.fail('请先选择申请区域等级')
        return
      }
      this.addressPicker = true
    },
    // 初始化区域管理员申请数据
    AreaApplyInitData() {
      AreaApplyInitData().then(res => {
        if (res) {
          this.applyInfo.userName = res.Data.ContactName
          this.applyInfo.userTel = res.Data.ContactTel
          this.applyInfo.userAddress = res.Data.ContactAddress
          this.bankList = res.Data.BankList
          this.bankList.forEach(item => {
            item.text = item.AccountName
            if (item.IsDefault) {
              this.bankInfo = item
            }
          })
          this.levelList = res.Data.LevelList
          this.levelList.forEach(item => {
            switch (item.Level) {
              case 3:
                item.text = '省级区域'
                break
              case 4:
                item.text = '市级区域'
                break
              case 5:
                item.text = '区级区域'
                break
              case 6:
                item.text = '街道区域'
                break
            }
          })
        }
      })
    },
    imageAfterRead(file) {
      if (file) {
        upLoad({
          Content: this.$utils.getCaption(file.content, 'base64,'),
          FileType: this.$utils.getCaption(file.file.type, '/')
        }).then(res => {
          if (res && res.Data) {
            this.tempImageArr.push({ url: res.Data.FullPath })
            var urlArr = []
            this.tempImageArr.forEach(item => {
              if (item.url) {
                urlArr.push(item.url)
              }
            })
            this.applyInfo.applyImages = urlArr.join(',')
          } else {
            if (this.imagesArr.length >= 1) {
              this.imagesArr.pop()
            } else {
              this.imagesArr = []
            }
            this.$toast.fail('上传图片失败，请重新上传')
          }
        })
      }
    },
    deleteImage(file, detail) {
      console.log(file, detail)
      var urlArr = []
      this.tempImageArr.splice(detail.index, 1)
      this.tempImageArr.forEach(item => {
        urlArr.push(item.url)
      })
      // this.tempImageArr = this.imagesArr
      this.applyInfo.applyImages = urlArr.join(',')
    },

    // 保存
    handleSubmit() {
      const _this = this
      this.$refs.subForm.validate().then(() => {
        if (!this.applyInfo.applyImages && this.applyInfo.payType === 1) {
          this.$toast.fail('请上传付款凭证')
          return
        }
				console.log(this.applyInfo,'本地路径')
				SubmitAreaApply(this.applyInfo).then(res => {
					if (res.Data) {
						//const msg = res.Msg || '提交成功，等待审核。'
						//this.$toast.success(msg)
						if(this.applyInfo.payType === 2 || this.applyInfo.payType === 1){
							window.location.href = this.$LocalDomain + '/m/user/areaapplylist'
						}else{
							window.location.href = this.$LocalDomain + '/m/user/AreaApplyPay?id=' + res.Data
            }
          }else{
						this.$toast(res.Msg)
					}
				})
			})
    }

  }
}
</script>
<style lang="scss" scoped>
.shadow-box{
  box-shadow: 0px 4px 8px 0px rgba(0, 0, 0, 0.1)
}
.right-triangle {
    padding-right: 32px;
    height: 48px;
    position: relative;
}
.right-triangle:after {
    content: '';
    position: absolute;
    display: inline-block;
    width: 0;
    height: 0;
    right: 0;
    top: 7px;
    transform: rotate( -45deg );
    border: 8px solid;
    border-color: transparent transparent #333 #333;
}
.bank-box{
  background: #F6F6F6;
  padding: 0 20px;

  .bank-list{
    position: relative;
    padding: 40px 10px 40px 0;
    &:before{
      border-color: #EAEAEA;
    }
  }
  .arrow{
    &:after{
      right: 30px;
      top: 50px;
      color: #969799;
      height: 12px;
      width: 12px;
    }
  }
  .bank-info{
    padding: 30px 0;
    font-size: 22px;
    .bank-info-title{
      width: 140px;
      text-align: justify;
      display: inline-block;
    }
  }
  .bank-img{
    text-align: center;
    padding: 30px 0;
    .img{
      margin: 0 auto;
    }
  }
}
.btn-box button:first-child{
  margin: 0;
}
.choose{
	margin-top: 30px;
	display: flex;
  justify-content: space-between;
}
.mb-30 img{
	width: 48px;
	height: 48px;
}
</style>
